//
//  PPGroupInviteController.m
//  pet
//
//  Created by 陈无忌 on 12/28/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPGroupInviteController.h"
#import "PPInviteFriendCell.h"
#import "PPInvitePreviewCell.h"

#import "PPSystemConfiguraton.h"
#import "EaseMob.h"

@interface PPGroupInviteController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (weak, nonatomic) PPSystemConfiguraton *config;
@property (strong, nonatomic) NSMutableArray *friendList;//邀请对象列表
@property (strong, nonatomic) NSMutableArray *inviteList;//用于环信
@property (weak, nonatomic) IBOutlet UICollectionView *inviteCollectionView;

@property (strong, nonatomic) NSMutableArray *inviteUserList;//用于collectionView展示

@end

@implementation PPGroupInviteController

- (NSMutableArray *)inviteList
{
    if (!_inviteList) {
        _inviteList = [NSMutableArray array];
    }
    return _inviteList;
}

- (NSMutableArray *)inviteUserList
{
    if (!_inviteUserList) {
        _inviteUserList = [NSMutableArray array];
    }
    return _inviteUserList;
}

-(PPSystemConfiguraton *)config
{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.inviteCollectionView.delegate = self;
    self.inviteCollectionView.dataSource = self;
    
    [self getFriendList];
}

-(void)getFriendList
{
    self.friendList = [self.config.friendArray mutableCopy];
    for (PPUserInfo *member in self.groupConversation.chatGroup.groupMember) {
        for (PPUserInfo *user in self.friendList) {
            if (user.id == member.id) {
                [self.friendList removeObject:user];
                break;
            }
        }
    }
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)invite:(id)sender {
    if (self.inviteUserList.count == 0) {
        [PPHUD hudShowWithString:@"请先邀请好友" andView:self.view];
        return;
    }
    //获得用户环信的邀请对象Id数组
    [self.inviteList removeAllObjects];
    for (PPUserInfo *user in self.inviteUserList) {
        NSString *idString = [NSString stringWithFormat:@"%d",user.id];
        [self.inviteList addObject:idString];
    }
    //获得要上传服务器的Id串
    NSString *idListString = @"";
    for (int i = 0;i < self.inviteList.count;i++ ) {
        NSString *idString = [self.inviteList objectAtIndex:i];
        idListString = [idListString stringByAppendingString:idString];
        idListString = [idListString stringByAppendingString:@","];
    }
    if (idListString.length > 0) {
        idListString = [idListString substringWithRange:NSMakeRange(0, idListString.length - 1)];
    }
    
    [[EaseMob sharedInstance].chatManager asyncAddOccupants:self.inviteList toGroup:self.groupConversation.targetId welcomeMessage:@"欢迎加入！" completion:
     ^(NSArray *occupants,EMGroup *group,NSString *welcomeMessage,EMError *error){
         if (!error) {
             NSString *url = [PPAPIList getAPIList].PPInviteJoinGroup;
             NSDictionary *params = @{@"easeMobGroupId":self.groupConversation.targetId,@"userIdString":idListString};
             [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
                 NSNumber *processResult = responseObject[@"processResult"];
                 if (processResult.boolValue) {
                     [PPHUD hudShowWithString:@"邀请成功" andView:self.view];
                     //back send notification
                     
                     NSString *queryUrl = [PPAPIList getAPIList].PPQueryConversationByTargetId;
                     NSDictionary *queryParams = @{@"userId":@(self.config.userInfo.id),@"targetId":self.groupConversation.targetId};
                     [httpRequst POST:queryUrl parameters:queryParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
                         NSError *err = nil;
                         NSDictionary *resultMap = responseObject[@"resultMap"];
                         NSDictionary *conversationDic = resultMap[@"conversation"];
                         PPConversation *conversation = [[PPConversation alloc] initWithDictionary:conversationDic error:&err];
                         self.groupConversation.chatGroup = conversation.chatGroup;
                         [[NSNotificationCenter defaultCenter] postNotificationName:@"memberChange" object:nil];
                         [self.navigationController popViewControllerAnimated:YES];
                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                         [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
                     }];
                     
                 }else{
                     [PPHUD hudShowWithString:@"邀请失败" andView:self.view];
                 }
             } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                 [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
             }];
         }else{
             [PPHUD hudShowWithString:@"邀请失败" andView:self.view];
         }
     }onQueue:nil];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.friendList.count;
}

-(BOOL)isEditing{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleInsert;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PPInviteFriendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"inviteCell"];
    PPUserInfo *user = [self.friendList objectAtIndex:indexPath.row];
    cell.userName.text = user.userName;
    [cell.avatar setImageWithURL:[PPImageUrl getImageUrlOriginal:user.userAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"select row%@",@(indexPath.row));
    PPUserInfo *user = [self.friendList objectAtIndex:indexPath.row];
    [self.inviteUserList addObject:user];
    [self.inviteCollectionView reloadData];
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"unselect row%@",@(indexPath.row));
    PPUserInfo *user = [self.friendList objectAtIndex:indexPath.row];
    [self.inviteUserList removeObject:user];
    [self.inviteCollectionView reloadData];
}

#pragma mark - Collection view data source
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.inviteUserList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PPInvitePreviewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"previewCell" forIndexPath:indexPath];
    PPUserInfo *user = [self.inviteUserList objectAtIndex:indexPath.row];
    [cell.avatar setImageWithURL:[PPImageUrl getImageUrlOriginal:user.userAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    return cell;
}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
